﻿using System.Linq.Expressions;

namespace WenAntdUI.Helps;

public static class DataBindingHelp
{
    public static T DataBinding<T, TData>(this T t, TData dataSource, string propertyName, string dataMember,
        Action<ConvertEventArgs>? format = null, Action<ConvertEventArgs>? parse = null)
    where T : IBindableComponent
    {
        var binding = new Binding(propertyName, dataSource, dataMember, false, DataSourceUpdateMode.OnPropertyChanged);
        binding.Format += (s, e) =>
        {
            format?.Invoke(e);
        };
        binding.Parse += (s, e) =>
        {
            parse?.Invoke(e);
        };
        t.DataBindings.Cast<Binding>()
            .Where(b => b.PropertyName == propertyName)
            .ToList()
            .ForEach(t.DataBindings.Remove);
        t.DataBindings.Add(binding);
        return t;
    }
    public static T DataBinding<T, TData>(this T t, TData dataSource, Expression<Func<T, TData, bool>> exception) where T : IBindableComponent
    {
        var body = exception.Body as BinaryExpression;

        //区分左右 避免 参数写成 b.xxx==a.xxx 无法识别
        var p = exception.Parameters;
        var left = body?.Left as MemberExpression;
        var right = body?.Right as MemberExpression;

        var tp = left?.Expression == p[0] ? left : right;
        var tdatap = left?.Expression != p[0] ? left : right;

        var propertyName = tp?.Member.Name;
        var dataMember = tdatap?.Member.Name;
        if (propertyName == null || dataMember == null)
            throw new Exception("参数获取错误");

        return t.DataBinding(dataSource, propertyName, dataMember);
    }


    public static T DataBinding<T, TData>(this T t, TData dataSource,
        Expression<Func<T, object>> controlExpr,
        Expression<Func<TData, object>> dataExpr)
        where T : IBindableComponent
    {
        var cMember = controlExpr.GetMemberName();
        var dMember = dataExpr.GetMemberName();
        return t.DataBinding(dataSource, cMember, dMember);
    }
}
